package com.xxh.blog.schedules;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxh.blog.entity.Essay;
import com.xxh.blog.service.essayService;
import com.xxh.blog.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 同步缓存与数据库的阅读量信息
 */
@Service
public class ViewCountAsy {

    @Autowired
    RedisUtil redisUtil;

    @Resource
    essayService essayService;

    //每分钟
    @Scheduled(cron = "0 */1 * * * ?")
    public void task() {
        System.out.println("========同步数据库的定时任务===========");
        Set<String> keys = redisUtil.keys("rank:essay:*");
        List<String> ids = new ArrayList<>();
        for (String key : keys) {
            if (redisUtil.hExists(key, "essay:viewcout")) {
                ids.add(key.substring("rank:essay:".length()));
            }
        }
        if (ids.isEmpty()) {
            return;
        }
        List<Essay> essays = essayService.list(new QueryWrapper<Essay>().in("id", ids));
        essays.stream().forEach(p -> {
            Integer count = Integer.parseInt((String) redisUtil.hGet("rank:essay:" + p.getId(), "essay:viewcout"));
            p.setViewCount(count);
        });
        if (essays.isEmpty()) {
            return;
        }
        //更新数据库的值（批量更新）
        boolean issucc = essayService.updateBatchById(essays);
        //更新成功，删除缓存的数据(面试题，你怎么保证数据库与缓存的一致性，答：数据库更新完成后删除缓存)
        if (issucc) {
            ids.stream().forEach(id -> {
                redisUtil.hDelete("rank:essay:" + id, "essay:viewcout");
            });
        }
    }
}
